import re
from django.db.models import Prefetch

from rest_framework import filters
from rest_framework import mixins
from rest_framework import permissions
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FileUploadParser

from django_filters.rest_framework import DjangoFilterBackend

from tool import restful
from tool.paginations import CommonPagination
from user.models import *
from .models import *
from .serializers import *
from rewrite.my_modelviewset import MyModelViewSet
from rewrite.my_mixins import MyListModelMixin, MyCreateModelMixin



# ProImg,Module,ProType,Project,Router,RouterMeta

# 模块图片
class ProImgViewSet(MyModelViewSet):
    """
    模块图片
    """
    queryset = ProImg.objects.filter(deleted__exact='0')            # 对应模型数据集和
    serializer_class = ProImgSerializer                             # 经过序列化器
    permission_classes = [permissions.IsAuthenticated]              # 权限限制
    pagination_class = CommonPagination                             # 分页
    # filter_backends = [DjangoFilterBackend, filters.OrderingFilter] # django过滤器
    # filterset_fields = ['name', 'category']                         # 过滤字段
    # search_fields = ['name']                                        # 查询字段
    # ordering_fields = ['order']                                     # 排序字段
    # ordering = ['order']                                            # 排序字段
# 模块图片下拉选
class ProImgOptionViewSet(MyModelViewSet):
    """
    模块图片下拉选
    """
    queryset = ProImg.objects.filter(deleted__exact='0')            # 对应模型数据集和
    serializer_class = ProImgOptionSerializer                       # 经过序列化器
    permission_classes = [permissions.IsAuthenticated]              # 权限限制
    pagination_class = CommonPagination                             # 分页
    # filter_backends = [DjangoFilterBackend, filters.OrderingFilter] # django过滤器
    # filterset_fields = ['name', 'category']                         # 过滤字段
    # search_fields = ['name']                                        # 查询字段
    # ordering_fields = ['order']                                     # 排序字段
    # ordering = ['order']                                            # 排序字段

#系统菜单
class ModuleViewSet(MyModelViewSet):
    """
    系统菜单
    """
    serializer_class = ModuleSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['name', 'category']
    ordering_fields = ['order']
    ordering = ['order']
    def get_queryset(self, *args, **kwargs):
        user_modules = self.request.user.modules
        if user_modules:
            user_modules = user_modules.split(',')
            user_modules = [i for i in user_modules if(len(str(i)) != 0)]
        else:
            user_modules = []
        projectID =  self.request.query_params.get("projectID", '')
        if projectID:
            pro_id = ','+str(projectID)+','
            return Module.objects.filter(category__exact='menu', id__in=user_modules, deleted__exact='0',projects__contains=pro_id).prefetch_related(Prefetch('sub_menu', queryset=Module.objects.filter(id__in=user_modules, deleted__exact='0',projects__contains=pro_id).order_by('order')))
        else:
            return Module.objects.filter(category__exact='menu', id__in=user_modules, deleted__exact='0').prefetch_related(Prefetch('sub_menu', queryset=Module.objects.filter(id__in=user_modules, deleted__exact='0').order_by('order')))
    def list(self, request, *args, **kwargs):
        """
        列出查询集.
        """
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            context = {
                'code': status.HTTP_200_OK,
                'msg': '查询成功！',
                'data': serializer.data
            }
            return self.get_paginated_response(context)
        serializer = self.get_serializer(queryset, many=True)
        i=0
        for menu in serializer.data:
            i=i+1
            menu['list']=i
        context = {
            'code': status.HTTP_200_OK,
            'msg': '查询成功！',
            'data': serializer.data
        }
        return Response(context)
#菜单下拉选
class ModuleOption(MyListModelMixin, viewsets.GenericViewSet):
    """菜单下拉选"""
    queryset = Module.objects.filter(deleted='0')
    serializer_class = ModuleOptionSerializer
    permission_classes = [permissions.IsAuthenticated]

# 模块类型
class ProTypeViewSet(MyModelViewSet):
    """
    模块类型
    """
    queryset = ProType.objects.filter(deleted__exact='0')            # 对应模型数据集和
    serializer_class = ProTypeSerializer                             # 经过序列化器
    permission_classes = [permissions.IsAuthenticated]              # 权限限制
    pagination_class = CommonPagination                             # 分页
    # filter_backends = [DjangoFilterBackend, filters.OrderingFilter] # django过滤器
    # filterset_fields = ['name', 'category']                         # 过滤字段
    # search_fields = ['name']                                        # 查询字段
    # ordering_fields = ['order']                                     # 排序字段
    # ordering = ['order']                                            # 排序字段
# 模块类型下拉选
class ProTypeOptionViewSet(MyModelViewSet):
    """
    模块类型下拉选
    """
    queryset = ProType.objects.filter(deleted__exact='0')            # 对应模型数据集和
    serializer_class = ProTypeOptionSerializer                       # 经过序列化器
    permission_classes = [permissions.IsAuthenticated]              # 权限限制
    pagination_class = CommonPagination                             # 分页
    # filter_backends = [DjangoFilterBackend, filters.OrderingFilter] # django过滤器
    # filterset_fields = ['name', 'category']                         # 过滤字段
    # search_fields = ['name']                                        # 查询字段
    # ordering_fields = ['order']                                     # 排序字段
    # ordering = ['order']                                            # 排序字段

# 应用模块
class ProjectViewSet(MyModelViewSet):
    """
    项目管理
    """
    queryset = Project.objects.filter(deleted__exact='0')
    serializer_class = ProjectSerializer
    permission_classes = [permissions.IsAuthenticated]
# 应用模块下拉选
class ProjectOptionViewSet(MyModelViewSet):
    """
    项目模块下拉选<br>
    search输入名称料号模糊查找<br>
    """
    # queryset = Role.objects.filter(deleted__exact='0')
    serializer_class = ProjectOptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    def get_queryset(self, *args, **kwargs):
        search = self.request.query_params.get("search")
        if  search:
            return Project.objects.filter(deleted__exact='0').filter(name__icontains=search)
        else:
            return Project.objects.filter(deleted__exact='0')

